import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'
import { encrypt,checkDigest,decrypt} from '@/utils/crypto' 
import router from '@/router'
let ROOT;
let mode;//判断是否加密
if (process.env.NODE_ENV === 'development') {
  //  ROOT = "/api"
   //ROOT = "http://47.90.96.229:7771/api/1/2/3"
  ROOT = "http://changchunback.yunjisi.fushoubainian.com/api/1/2/3"
  //ROOT = "http://47.90.96.229:7771/api/1/2/3"
  //ROOT = 'http://192.168.1.68:7771/api/1/2/3'
  mode=3
} else {
  // ROOT = window.ROOT;
  //ROOT = "http://47.90.96.229:7771/api/1/2/3"
  //ROOT = 'http://192.168.1.166:7771/api/1/2/3'
  ROOT = "http://changchunback.yunjisi.fushoubainian.com/api/1/2/3"
  mode=3
}
var service = axios.create({
  // baseURL: "http://139.196.106.25:8001/fmis-api/api", // url = base url + request url
  // baseURL: "http://127.0.0.1:8001/fmis", // url = base url + request url
  // baseURL: ROOT, // url = base url + request url
  baseURL: ROOT, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 ,// request timeout
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json'
  }
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let ts=(new Date()).valueOf();//时间戳
    let token = getToken()
    if (token) {
      config.headers['token'] = token
    }
     console.log(config.data,'加密前参数')
    if(mode===3){
      config.data=encrypt(JSON.stringify(config.data));
      console.log(config.data,'加密后参数')
    }else if(mode===0){
      let postData={
        msgId:'uid',
        token,
        mode:0,
        body:JSON.stringify(config.data),
        digest:null,
        ts
      }
      console.log(postData,'铭文状态传输数据')
      config.data=postData
    }
    
    // console.log(config.data,'加密后参数')
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
     return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log(response,'888')
    if (response.data.result == -99) {   //token 失效
      removeToken()
      router.push("/login");
      location.reload()
    }
    if(response.data.mode==3){
      var res = response.data
      if (res.result != 0) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
  
        if (res.code == 2) {   //token 失效
          removeToken()
          router.push("/login");
          location.reload()
        }
        return Promise.reject(new Error(res.message || 'Error')).catch(err => {
          // console.log(err) // 这里catch到错误
        })
      } else {
        // console.log(res,'验签数据')
            //先验签报文摘要
          let flag=checkDigest(res.digest,res.body,res.ts);
          console.log(flag,'校验结果')
          if(flag){
            let result=decrypt(res.body,'UX00H5n2BN7L4Y5H');
              console.log(result,result.code,result.data,'7878')
              console.log('result')
              console.log(result)
            // return data
            // if(result.code===1){
            //   this.$message({
  
            //   })
            // }else{
            //   this.$message.error(result.message)
            // }
            return result
          }else{
            this.$message.error("验签失败");
            return false
          }
        }
    }else if(response.data.mode==0) {
      if(response.data.result!=0){
        this.$message.error('请求数据错误')
        return 
      }
      //不需要解密
      var res = response.data.body
      if (res.code == 1) {
        return res
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
  
        if (res.code == 2) {   //token 失效
          removeToken()
          router.push("/login");
          location.reload()
        }
        return Promise.reject(new Error(res.message || 'Error')).catch(err => {
          // console.log(err) // 这里catch到错误
        })
      }
    }
    
    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
   
  },
  error => {
     console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // return Promise.reject(error)
  }
)

export default service
